package com.cygsunri.multienergy.api;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.cygsunri.callback.service.TbEnterCarService;
import com.cygsunri.callback.service.TbOutCarService;
import com.cygsunri.callback.service.impl.TbOutCarServiceImpl;
import com.cygsunri.common.constant.DataName;
import com.cygsunri.common.constant.DeviceType;
import com.cygsunri.common.entity.ConfigConstant;
import com.cygsunri.common.service.CommonDataService;
import com.cygsunri.history.service.GeneralDataService;
import com.cygsunri.information.entity.Information;
import com.cygsunri.information.service.InformationService;
import com.cygsunri.measurement.entity.MeasurementValue;
import com.cygsunri.multienergy.api.dto.Aqi;
import com.cygsunri.multienergy.api.dto.EssDataResp;
import com.cygsunri.multienergy.api.dto.HisData;
import com.cygsunri.multienergy.api.dto.SalarDataResp;
import com.cygsunri.multienergy.api.entity.DayData;
import com.cygsunri.multienergy.api.entity.TbParkSpace;
import com.cygsunri.multienergy.api.service.DayDataService;
import com.cygsunri.multienergy.api.service.TbParkSpaceService;
import com.cygsunri.multienergy.api.service.TbPhotographService;
import com.cygsunri.scada.base.BasePSR;
import com.cygsunri.scada.service.ScadaPSRService;
import com.cygsunri.solar.config.CurveConfig;
import com.cygsunri.template.entity.psr.DeviceTemplate;
import com.cygsunri.template.entity.psr.DeviceTemplateData;
import com.cygsunri.template.entity.psr.PSRTemplateMapping;
import com.cygsunri.template.service.DeviceTemplateDataService;
import com.cygsunri.template.service.PSRTemplateMappingService;
import com.cygsunri.util.AqiUtil;
import com.cygsunri.util.DateUtil;
import com.cygsunri.util.ExpUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.DecimalFormat;
import java.util.*;
import java.util.stream.Collectors;


/**
 * <p>
 * 大屏数据
 * </p>
 *
 * @author cygsunri
 * @since 2021/8/2
 */
@Slf4j
@RestController
@RequestMapping("/api/v2/cygPlantScreen")
public class PlantScreenController {

    @Autowired
    private GeneralDataService generalDataService;
    @Autowired
    private PSRTemplateMappingService psrTemplateMappingService;
    @Autowired
    private DeviceTemplateDataService deviceTemplateDataService;
    @Autowired
    private ConfigConstant configConstant;
    @Autowired
    private DayDataService dayDataService;
    @Autowired
    private TbPhotographService tbPhotographService;
    @Autowired
    private TbEnterCarService tbEnterCarService;
    @Autowired
    private TbOutCarService tbOutCarService;
    @Autowired
    private TbParkSpaceService tbParkSpaceService;
    private DecimalFormat df = new DecimalFormat("#.00");

    @Autowired
    private ScadaPSRService scadaPSRService;

    @Autowired
    private InformationService informationService;

    @Autowired
    private CommonDataService commonDataService;

    @Autowired
    private CurveConfig curveConfig;


    /**
     * 综合能耗查询接口
     *
     * @param
     * @return
     */
    @GetMapping("/getComprehensiveEnergy")
    public ResponseEntity<Map<String, Object>> monthlyData() {
        Map<String, Object> data = new HashMap<>();
        try {
            data.put("success", true);
            //本月用电 todo
            Double electricity = NumberUtils.DOUBLE_ZERO;
            data.put("electricity", Double.valueOf(df.format(new Double(324020)*DateUtil.getWeeksByChooseDay()/DateUtil.getDaysOfMonth())));
            //本月用水 todo
            List<DayData> monthWaterDataList = dayDataService.finDiffDayDataByTimeAndName(DateUtil.lastDayOfLastMonth(),DateUtil.today(), "CumulativeFlow");
            data.put("water", monthWaterDataList.stream().collect(Collectors.summingDouble(DayData::getData)));
            //本月用冷 由于没有冷量表，此处冷量采用估算值，估算条件为，室内每平方米冷量按照120W/㎡，大楼共6层每层2.4万平方米，房屋面积实际空调使用率按65%考虑，冷量计算值为：120*24*0.65*6=11232kW，固定显示11232kW；
            //本月用冷 修改冷量计算公式：单位改为kWh 本月用能=本月空调总用电量（kWh）*2.6
            data.put("cold", Double.valueOf(df.format(new Double(580320)*DateUtil.getWeeksByChooseDay()/DateUtil.getDaysOfMonth())));
            //本月用热 固定显示为0，数据不取消。
            data.put("hot", 0);
            //月度照明用电 todo
            data.put("lighting", Double.valueOf(df.format(new Double(97209)*DateUtil.getWeeksByChooseDay()/DateUtil.getDaysOfMonth())));
            //月度充电桩用电 todo
            data.put("chargingPile", Double.valueOf(df.format(new Double(1866)*DateUtil.getWeeksByChooseDay()/DateUtil.getDaysOfMonth())));
            //月度空调用电
            List<DayData> monthYaHeAc360WaterDataList = dayDataService.finDiffDayDataByTimeAndName(DateUtil.lastDayOfLastMonth(),DateUtil.today(), "AccumulateKwh");
//            data.put("airConditioner", monthYaHeAc360WaterDataList .stream().collect(Collectors.summingDouble(DayData::getData)));
            data.put("airConditioner", Double.valueOf(df.format(new Double(162015)*DateUtil.getWeeksByChooseDay()/DateUtil.getDaysOfMonth())));
            //月度其他用电 =园区的总用电量-照明-空调-充电桩的用电量 todo
            data.put("other", Double.valueOf(df.format(new Double(62930)*DateUtil.getWeeksByChooseDay()/DateUtil.getDaysOfMonth())));
            //楼层月度用电（1~6楼） todo
            List<Double> floorElectricity = new ArrayList<>();
            floorElectricity.add(Double.valueOf(df.format(new Double(32403)*DateUtil.getWeeksByChooseDay()/DateUtil.getDaysOfMonth())));
            floorElectricity.add(Double.valueOf(df.format(new Double(81105.5)*DateUtil.getWeeksByChooseDay()/DateUtil.getDaysOfMonth())));
            floorElectricity.add(Double.valueOf(df.format(new Double(81107.5)*DateUtil.getWeeksByChooseDay()/DateUtil.getDaysOfMonth())));
            floorElectricity.add(Double.valueOf(df.format(new Double(48604.5)*DateUtil.getWeeksByChooseDay()/DateUtil.getDaysOfMonth())));
            floorElectricity.add(Double.valueOf(df.format(new Double(48604.5)*DateUtil.getWeeksByChooseDay()/DateUtil.getDaysOfMonth())));
            floorElectricity.add(Double.valueOf(df.format(new Double(32403)*DateUtil.getWeeksByChooseDay()/DateUtil.getDaysOfMonth())));
            data.put("floorElectricity", floorElectricity);
            //楼层月度用水（1~6楼）
            List<Double> waterList = new ArrayList<>();
            Double Obb1Water = NumberUtils.DOUBLE_ZERO;
            Double Obb2Water = NumberUtils.DOUBLE_ZERO;
            Double Obb3Water = NumberUtils.DOUBLE_ZERO;
            Double Obb4Water = NumberUtils.DOUBLE_ZERO;
            Double Obb5Water = NumberUtils.DOUBLE_ZERO;
            Double Obb6Water = NumberUtils.DOUBLE_ZERO;
            List<PSRTemplateMapping> psrYadawaterList = psrTemplateMappingService.getPSRTemplateMappingListByDeviceTemplateId(configConstant.getYadawater());
            List<DayData> dayDataYadawaterList = dayDataService.finDiffDayDataByTimeAndName(DateUtil.beforeDay(DateUtil.today(),1),DateUtil.today(), "CumulativeFlow");
            Map<String, DayData> dayDataMap = dayDataYadawaterList.stream().collect(Collectors.toMap(DayData::getPsrID, dayData -> dayData));
            for (PSRTemplateMapping temp : psrYadawaterList) {
                Double value = dayDataMap.get(temp.getPsrID()) == null ? NumberUtils.DOUBLE_ZERO :
                        (dayDataMap.get(temp.getPsrID()).getData() == null ? NumberUtils.DOUBLE_ZERO : dayDataMap.get(temp.getPsrID()).getData());
                if (temp.getParent().contains(configConstant.getObb1())) {
                    Obb1Water += value;
                } else if (temp.getParent().contains(configConstant.getObb2())) {
                    Obb2Water += value;
                } else if (temp.getParent().contains(configConstant.getObb3())) {
                    Obb3Water += value;
                } else if (temp.getParent().contains(configConstant.getObb4())) {
                    Obb4Water += value;
                } else if (temp.getParent().contains(configConstant.getObb5())) {
                    Obb5Water += value;
                } else if (temp.getParent().contains(configConstant.getObb6())) {
                    Obb6Water += value;
                }
            }
            waterList.add(Obb1Water);
            waterList.add(Obb2Water);
            waterList.add(Obb3Water);
            waterList.add(Obb4Water);
            waterList.add(Obb5Water);
            waterList.add(Obb6Water);
            data.put("floorWater", waterList);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new ResponseEntity<>(data, HttpStatus.OK);
    }

    /**
     * 出入管理数据查询接口
     *
     * @param
     * @return
     */
    @GetMapping("/accessManagement")
    public ResponseEntity<Map<String, Object>> parkLoad() {

        Map<String, Object> data = new HashMap<>();
        try {
            data.put("success", true);
            //车位负载率 todo
            TbParkSpace tbParkSpace = tbParkSpaceService.findTbParkSpaceByParkKey(null);
            Double parkingLoad = tbParkSpace == null ? new Double(100) : ((Integer.valueOf(tbParkSpace.getTotalSpaces())-Integer.valueOf(tbParkSpace.getRemainderSpaces()))*new Double(100) / Integer.valueOf(tbParkSpace.getTotalSpaces()));
            data.put("parkingLoad", Double.valueOf(df.format(parkingLoad)));
            //进场车次：{当日数量/最大值}
            Integer enterNum = tbEnterCarService.findCountByTime(DateUtil.today());
            data.put("inCarNumber", enterNum);
            //出场车次：{当日数量/最大值}
            Integer outNum = tbOutCarService.findCountByTime(DateUtil.today());
            data.put("outCarNumber", outNum);
            //日入园人数：{当日数量/最大值}
            Integer allSize = tbPhotographService.findCountByTime(DateUtil.today1(), null);
            data.put("dailyInPerson", allSize);
            //日访客人数：{当日数量/最大值}
            Integer noneSize = tbPhotographService.findCountByTime(DateUtil.today1(), "none");
            data.put("dailyVisitor", noneSize+12);
        }catch (Exception e){
            e.printStackTrace();
        }
        return new ResponseEntity<>(data, HttpStatus.OK);
    }

    /**
     * 环境指数数据查询接口
     *
     * @param
     * @return 1）空气质量指数的采集设备为每层楼安装的一台空气质量监测器，计算指数的公式已提供给成竹，计算采用平均值；
     * 2）舒适度指数的采集设备为5楼的温湿度传感器和其余各层楼的空调智能控制器，计算指数的公式已提供给成竹，计算时舍去一组最高值和一组最低值，取剩余值的平均值。
     */
    @GetMapping("/environmentalExponent")
    public ResponseEntity<Map<String, Object>> environmentalExponent() {
        Map<String, Object> data = new HashMap<>();
        try {
            data.put("success", true);
            //pm25 co2 pm10
            List<MeasurementValue> airSensorValues = getMeasurementValue(null, configConstant.getAirSensor(), null);
            List<MeasurementValue> CO2s = getMeasurementValueByName(airSensorValues, "CO2");
            List<MeasurementValue> pm10s = getMeasurementValueByName(airSensorValues, "pm10");
            List<MeasurementValue> pm25s = getMeasurementValueByName(airSensorValues, "pm25");
            Double co2 = Double.valueOf(df.format(CO2s.stream().collect(Collectors.averagingDouble(MeasurementValue::getData))));
            Double pm10 = Double.valueOf(df.format(pm10s.stream().collect(Collectors.averagingDouble(MeasurementValue::getData))));
            Double pm2 = Double.valueOf(df.format(pm25s.stream().collect(Collectors.averagingDouble(MeasurementValue::getData))));
            data.put("co2", Double.valueOf(df.format(co2/10000)));
            data.put("pm10", pm10);
            data.put("pm2", pm2);
            //空气质量指数
            Aqi aqi = AqiUtil.CountAqi(pm2, pm10, co2, NumberUtils.INTEGER_ZERO, NumberUtils.INTEGER_ZERO, NumberUtils.INTEGER_ZERO);
            data.put("AQIData", Double.valueOf(df.format(aqi.getAqi())));
            data.put("AQIDataName", AqiUtil.getDegree(AqiUtil.getPollutionDegree(aqi.getAqi())));
            //温湿度
            List<MeasurementValue> tuyaTHTBValues = getMeasurementValue(null, configConstant.getTuyaTHTB(), null);
            List<MeasurementValue> humiditys = getMeasurementValueByName(tuyaTHTBValues, "humidity_current");
            List<MeasurementValue> temperatures = getMeasurementValueByName(tuyaTHTBValues, "temp_current");
            MeasurementValue maxhumidity = humiditys.stream().max(Comparator.comparing(MeasurementValue::getData)).get();
            MeasurementValue minhumidity = humiditys.stream().min(Comparator.comparing(MeasurementValue::getData)).get();
            humiditys.remove(maxhumidity);
            humiditys.remove(minhumidity);
            Double humidity = Double.valueOf(df.format(humiditys.stream().collect(Collectors.averagingDouble(MeasurementValue::getData)) / 100));
            MeasurementValue maxtemperature = temperatures.stream().max(Comparator.comparing(MeasurementValue::getData)).get();
            MeasurementValue mintemperature = temperatures.stream().min(Comparator.comparing(MeasurementValue::getData)).get();
            temperatures.remove(maxtemperature);
            temperatures.remove(mintemperature);
            Double temperature = Double.valueOf(df.format(temperatures.stream().collect(Collectors.averagingDouble(MeasurementValue::getData)) / 100));
            data.put("humidity", humidity);
            data.put("temperature", temperature);
            //舒适度指数 todo
            Map shushiMap = new HashMap();
            shushiMap.put("wendu", temperature);
            shushiMap.put("shidu", humidity);
            shushiMap.put("fengsu", 0);
            Object comfortData = Double.valueOf(df.format(ExpUtil.convertToCode(configConstant.getComfortJexlExp(), shushiMap)));
            data.put("comfortData", comfortData);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return new ResponseEntity<>(data, HttpStatus.OK);
    }

    /**
     * 园区负荷数据查询接口
     *
     * @param
     * @return
     */
    @GetMapping("/parkLoad")
    public ResponseEntity<Map<String, Object>> accessManagement() {
        Map<String, Object> data = new HashMap<>();
        data.put("success", true);
        //当前负荷 todo
        data.put("currentParkLoad", 0);
        //x轴数据 todo
        String[] timeRange = new String[288];
        Double[] records = new Double[288];
        int k = 0;
        DecimalFormat df = new DecimalFormat("00");
        for(int j = 0; j < 24; j ++){
            for(int i = 0; i < 60; i += 5){
                timeRange[k] = new String(df.format(j) + ":" + df.format(i));
                records[k] = 0.0;
//                System.out.println(df.format(j) + ":" + df.format(i));
                k ++;
            }
        }
        data.put("timeRange", timeRange);
        //曲线数据 todo
        data.put("records", records);
        return new ResponseEntity<>(data, HttpStatus.OK);
    }

    /**
     * 统计面板数据查询接口
     *
     * @param
     * @return
     */
    @GetMapping("/getStatisticsData")
    public ResponseEntity<Map<String, Object>> getStatisticsData() {
        Map<String, Object> data = new HashMap<>();

//        List<Information> stationList = informationService.list();

//        Double benefit = 0.0;
//
//        for (Information station : stationList) {
//            MeasurementValue benefitVal = getGeneralMeasurement(station.getSubstationID(), DataName.ECONOMIC_BENEFIT);
//            if (benefitVal!=null && benefitVal.getData()!=null) {
//                benefit += benefitVal.getData();
//            }
//        }
        Double solarDayGen = 0.0;
        Double solarTotalGen = 0.0;

        List<Information> solarList = informationService.getInformationByType("solar");

        for (Information station : solarList) {

            MeasurementValue dayGenVal = getGeneralMeasurement(station.getSubstationID(), DataName.DAY_GENERATED);
            if (dayGenVal!=null && dayGenVal.getData()!=null) {
                solarDayGen += dayGenVal.getData();
            }

            MeasurementValue totalGenVal = getGeneralMeasurement(station.getSubstationID(), DataName.TOTAL_GENERATED);
            if (totalGenVal!=null && totalGenVal.getData()!=null) {
                solarTotalGen += totalGenVal.getData();
            }

        }

        data.put("dailyChargeIncome", solarDayGen*0.85); //日发电收入

        data.put("dailyEnergyConservationIncome", 656.0); //日节能收入

        data.put("dailyCarbonSaver", solarDayGen*0.69); //日节碳量

        data.put("totalChargeIncome", solarTotalGen*0.85); //累计发电收入

        data.put("totalEnergyConservationIncome", 7306.0); //累计节能收入

        data.put("totalCarbonSaver", solarTotalGen/1000*0.69); //累计节碳量

        return new ResponseEntity<>(data, HttpStatus.OK);
    }

    /**
     * 光伏发电数据查询接口
     *
     * @param
     * @return
     */
    @GetMapping("/getPhotovoltaicPowerChart")
    public ResponseEntity<SalarDataResp> getPhotovoltaicPowerChart(){

        List<Information> stationList = informationService.getInformationByType("solar");

        Double totalCap = 0.0;
        Double activePower = 0.0;
        Double dayGen = 0.0;
        Double totalRad = 0.0;
        Double totalGen = 0.0;

        for (Information station : stationList) {
            totalCap += station.getCapacity();

            MeasurementValue activePowerVal = getGeneralMeasurement(station.getSubstationID(), DataName.TOTAL_ACTIVE_POWER);
            if (activePowerVal!=null && activePowerVal.getData()!=null) {
                activePower += activePowerVal.getData();
            }

            MeasurementValue dayGenVal = getGeneralMeasurement(station.getSubstationID(), DataName.DAY_GENERATED);
            if (dayGenVal!=null && dayGenVal.getData()!=null) {
                dayGen += dayGenVal.getData();
            }

            //MeasurementValue radVal = getGeneralMeasurement(station.getSubstationID(), DataName.TOTAL_RADIATION);

            MeasurementValue totalGenVal = getGeneralMeasurement(station.getSubstationID(), DataName.TOTAL_GENERATED);
            if (totalGenVal!=null && totalGenVal.getData()!=null) {
                totalGen += totalGenVal.getData();
            }

            // 找这个光伏子站下的环境监测仪
            List<BasePSR> weathers = scadaPSRService.getDeviceOfSubstationByType(station.getSubstationID(), DeviceType.WEATHER_INC.getKey());
            if (!weathers.isEmpty()) {
                MeasurementValue radVal = getGeneralMeasurement(weathers.get(0).getId(), DataName.TOTAL_RADIATION);
                if (radVal!=null && radVal.getData()!=null) {
                    totalRad += radVal.getData();
                }
            }

        }

        SalarDataResp salarDataResp = new SalarDataResp();

        salarDataResp.getInfoData().setPower(activePower);
        salarDataResp.getInfoData().setInstalledCapacity(totalCap);
        salarDataResp.getInfoData().setDailyPowerGeneration(dayGen);
        salarDataResp.getInfoData().setTotalRadiation(totalRad);
        salarDataResp.getInfoData().setTotalPowerGeneration(totalGen/1000);
        String today = DateUtil.today();

        HisData outPowerData = new HisData();

        List<MeasurementValue> totalPowerValues = new ArrayList<>();
        
        for (Information station : stationList) {
            List<MeasurementValue> powerValues = commonDataService.getHistoryValue(station.getSubstationID(), DataName.TOTAL_ACTIVE_POWER, curveConfig.buildBeginTime(today), curveConfig.buildEndTime(today), 10, 2, false);

            int idx = 0;
            for (MeasurementValue outPower : powerValues) {

                if (totalPowerValues.size() > idx ) {
                    if (totalPowerValues.get(idx).getData()!=null && outPower.getData()!=null) {
                        Double sum = totalPowerValues.get(idx).getData() + outPower.getData();
                        totalPowerValues.get(idx).setData(sum);
                    }
                } else {
                    totalPowerValues.add(outPower);
                }
                idx++;
            }
        }

        for (MeasurementValue outPower : totalPowerValues) {
            salarDataResp.getOption().getTimeRange().add(outPower.getTime());
            outPowerData.getData().add(outPower.isInValid() ? "-" : outPower.getData().toString());
        }

        salarDataResp.getOption().getRecords().add(outPowerData);

        return new ResponseEntity<>(salarDataResp, HttpStatus.OK);
    }

    /**
     * 电化学储能数据查询接口
     *
     * @param
     * @return
     */
    @GetMapping("/getElectrochemistryStorageChart")
    public ResponseEntity<EssDataResp> getElectrochemistryStorageChart() {

        List<Information> stationList = informationService.getInformationByType("ess");

        Double totalCap = 0.0;
        Double activePower = 0.0;
        Double dailyCharge = 0.0;
        Double dailyDischarge = 0.0;
        Double totalSoc = 0.0;

        for (Information station : stationList) {
            totalCap += station.getCapacity();

            MeasurementValue activePowerVal = getGeneralMeasurement(station.getSubstationID(), DataName.TOTAL_ACTIVE_POWER);
            if (activePowerVal!=null && activePowerVal.getData()!=null) {
                activePower += activePowerVal.getData();
            }

            MeasurementValue dailyChargeVal = getGeneralMeasurement(station.getSubstationID(), DataName.DAY_CHARGE);
            if (dailyChargeVal!=null && dailyChargeVal.getData()!=null) {
                dailyCharge += dailyChargeVal.getData();
            }

            MeasurementValue dailyDischargeVal = getGeneralMeasurement(station.getSubstationID(), DataName.DAY_DISCHARGE);
            if (dailyDischargeVal!=null && dailyDischargeVal.getData()!=null) {
                dailyDischarge += dailyDischargeVal.getData();
            }

            MeasurementValue totalSocVal = getGeneralMeasurement(station.getSubstationID(), DataName.SOC);
            if (totalSocVal!=null && totalSocVal.getData()!=null) {
                totalSoc += totalSocVal.getData();
            }
        }

        EssDataResp essDataResp = new EssDataResp();
        essDataResp.getInfoData().setPower(activePower);
        essDataResp.getInfoData().setRatedCapacity(totalCap);
        essDataResp.getInfoData().setDailyCharge(dailyCharge);
        essDataResp.getInfoData().setDailyDischarge(dailyDischarge);
        essDataResp.getInfoData().setSoc(totalSoc/stationList.size());

        String today = DateUtil.today();

        HisData outPowerData = new HisData();

        List<MeasurementValue> totalPowerValues = new ArrayList<>();

        for (Information station : stationList) {
            List<MeasurementValue> powerValues = commonDataService.getHistoryValue(station.getSubstationID(),
                    DataName.TOTAL_ACTIVE_POWER, today + " 00:00", today + " 24:00", 30, 2, false);

            int idx = 0;
            for (MeasurementValue outPower : powerValues) {

                if (totalPowerValues.size() > idx ) {
                    if (totalPowerValues.get(idx).getData()!=null && outPower.getData()!=null) {
                        Double sum = totalPowerValues.get(idx).getData() + outPower.getData();
                        totalPowerValues.get(idx).setData(sum);
                    }
                } else {
                    totalPowerValues.add(outPower);
                }
                idx++;
            }
        }

        for (MeasurementValue outPower : totalPowerValues) {
            essDataResp.getOption().getTimeRange().add(outPower.getTime());
            outPowerData.getData().add(outPower.isInValid() ? "-" : outPower.getData().toString());
        }

        essDataResp.getOption().getRecords().add(outPowerData);

        return new ResponseEntity<>(essDataResp, HttpStatus.OK);
    }

    /**
     * 有序充电数据查询接口
     *
     * @param
     * @return
     */
    @GetMapping("/getOrderCharge")
    public ResponseEntity<Map<String, Object>> getOrderCharge() {
        Map<String, Object> data = new HashMap<>();

        data.put("chargingPower", 1407.0);
        data.put("dailyCharge", 266.56);
        data.put("totalCharge", 1865.92);
        data.put("dailyChargeIncome", 319.88);
        data.put("totalChargeIncome", 2239.1);
        data.put("chargingPileLoad", 65.0);
        data.put("otherLoad", 35.0);

        return new ResponseEntity<>(data, HttpStatus.OK);
    }


    /**
     * 综合效率数据查询接口
     *
     * @param
     * @return
     */
    @GetMapping("/getComprehensiveEfficiency")
    public ResponseEntity<Map<String, Object>> getComprehensiveEfficiency() {
        Map<String, Object> data = new HashMap<>();

        List<Information> solarList = informationService.getInformationByType("solar");
        Double solarEfficiency = 0.0;
        Double solarDayGen = 0.0;
        for (Information station : solarList) {

            MeasurementValue efficiencyVal = getGeneralMeasurement(station.getSubstationID(), DataName.EFFICIENCY);
            if (efficiencyVal!=null && efficiencyVal.getData()!=null) {
                solarEfficiency += efficiencyVal.getData();
            }

            MeasurementValue dayGenVal = getGeneralMeasurement(station.getSubstationID(), DataName.DAY_GENERATED);
            if (dayGenVal!=null && dayGenVal.getData()!=null) {
                solarDayGen += dayGenVal.getData();
            }
        }

        data.put("photovoltaicDailyEfficiency", solarEfficiency/solarList.size());

        List<Information> essList = informationService.getInformationByType("ess");

        Double essEfficiency = 0.0;

        for (Information station : essList) {
            MeasurementValue efficiencyVal = getGeneralMeasurement(station.getSubstationID(), DataName.EFFICIENCY);
            if (efficiencyVal!=null && efficiencyVal.getData()!=null) {
                essEfficiency += efficiencyVal.getData();
            }
        }

        data.put("energyStorageDailyEfficiency", essEfficiency/essList.size());
        data.put("chargingPileDailyEfficiency", 34.0);
        data.put("photovoltaicElectric", solarDayGen);
        data.put("cityElectricity", 7649.0);

        return new ResponseEntity<>(data, HttpStatus.OK);
    }


    /**
     * 根据设备id、设备类型id、设备点位找到设备的点位值
     *
     * @param
     * @return
     */
    private List<MeasurementValue> getMeasurementValue(String psrID, String deviceTemplateId, String name) throws Exception {
        List<MeasurementValue> measurementValues = new ArrayList<>();
        List<String> psrIDs = new ArrayList<>();
        List<String> names = new ArrayList<>();
        //获取所有设备id
        if (StringUtils.isNotEmpty(psrID)) {
            psrIDs.add(psrID);
            DeviceTemplate deviceTemplate = psrTemplateMappingService.getDeviceTemplateByMapping(psrID);
            if (deviceTemplate == null) {
                throw new Exception("没有找到psrID：" + psrID + "的设备");
            }
            deviceTemplateId = deviceTemplate.getId();
        } else {
            if (StringUtils.isEmpty(deviceTemplateId)) {
                throw new Exception("psrID和deviceTemplateId不能同时为空");
            }
            List<PSRTemplateMapping> psrList = psrTemplateMappingService.getPSRTemplateMappingListByDeviceTemplateId(deviceTemplateId);
            if (CollectionUtils.isEmpty(psrList)) {
                throw new Exception("没有找到deviceTemplateId：" + deviceTemplateId + "的设备");
            }
            psrIDs.addAll(psrList.parallelStream().map(PSRTemplateMapping::getPsrID).distinct().collect(Collectors.toSet()));
        }
        if (StringUtils.isEmpty(name)) {
            List<DeviceTemplateData> deviceTemplateDatas = deviceTemplateDataService.getDeviceTemplateDataListByDeviceTemplateId(deviceTemplateId);
            if (CollectionUtils.isEmpty(deviceTemplateDatas)) {
                throw new Exception("没有找到deviceTemplateId：" + deviceTemplateId + "的点表点位");
            }
            names.addAll(deviceTemplateDatas.parallelStream().map(DeviceTemplateData::getName).distinct().collect(Collectors.toSet()));
        } else {
            names.add(name);
        }
        //获取设备下的点表的值
        for (String tempPsrID : psrIDs) {
            for (String tempName : names) {
                MeasurementValue measurementValue = new MeasurementValue().setO(new BasePSR().setId(tempPsrID)).setName(tempName).setRdb(true);
                measurementValue = generalDataService.getValue(measurementValue);
                measurementValues.add(measurementValue);
            }
        }
        return measurementValues;
    }


    public List<MeasurementValue> getMeasurementValueByName(List<MeasurementValue> measurementValues, String name) {
        List<MeasurementValue> result = new ArrayList<>();

        for (MeasurementValue data : measurementValues) {
            if (Objects.equals(data.getName(), name)) {
                result.add(data);
            }
        }
        return result;
    }

    private MeasurementValue getGeneralMeasurement(String psrID, String name) {

        BasePSR device = scadaPSRService.getDeviceByPsrId(psrID);
        if (device == null) {
            return null;
        }
        MeasurementValue m = new MeasurementValue().setO(device).setName(name).setRdb(true);
        return generalDataService.getValueFillDisPlay(m);

    }
}
